package com.example.pdfandword.word;

import com.example.pdfandword.controller.TableEntity;
import org.apache.commons.jexl3.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import java.io.*;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;

public class WordTemplateUtilities {
    private static final WordTemplateUtilities word = new WordTemplateUtilities();

    private static WordTemplate template;

    private WordTemplateUtilities() {
    }

    public static WordTemplateUtilities GetInstance() {
        return word;
    }

    public synchronized void toWord(File intfile, String outfilePath, Map<String, Object> map) {
        FileInputStream fileInputStream = null;
        File outfile = new File(outfilePath);
        FileOutputStream out;
        try {
            fileInputStream = new FileInputStream(intfile);
            template = new WordTemplate(fileInputStream);

            template.replaceTag(map);

            out = new FileOutputStream(outfile);
            BufferedOutputStream bos = new BufferedOutputStream(out);
            template.write(bos);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

	public static void convertWordToPdf(String wordPath, String pdfPath) throws IOException {

		FileInputStream inpuFile = new FileInputStream(wordPath);
		File outFile=new File(pdfPath);

	    //从输入的文件流创建对象
	    XWPFDocument document = new XWPFDocument(inpuFile);

	    //创建PDF选项
	    PdfOptions pdfOptions = PdfOptions.create();//.fontEncoding("windows-1250")

	    //为输出文件创建目录
	    outFile.getParentFile().mkdirs();

	    //执行PDF转化
	    PdfConverter.getInstance().convert(document, new FileOutputStream(outFile), pdfOptions);

	    System.out.println("成功转换:"+pdfPath);

	}


    /**
     * 动态替换docx 表格内容 并下载
     */
    public static void downloadWord(List<TableEntity> list,String[] strs, String inFilePath, String outFilePath){


        //添加表格
        try {
            XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(inFilePath));// 生成word文档并读取模板

            //换行
            XWPFParagraph paragraph2 = document.createParagraph();
            XWPFRun paragraphRun2 = paragraph2.createRun();
            paragraphRun2.setText("\r");

            //附表格
            XWPFTable ComTable = document.createTable();
            int siz = ComTable.getRows().size();
            //列宽自动分割
            /*CTTblWidth comTableWidth = ComTable.getCTTbl().addNewTblPr().addNewTblW();
            comTableWidth.setType(STTblWidth.DXA);
            comTableWidth.setW(BigInteger.valueOf(9072));*/

            //表格第一行
            XWPFTableRow comTableRowOne = ComTable.getRow(0);
            // 表格标题内容的填充
            // 因为document.createTable() 创建表格后默认是一行一列，所以第一行第一列是直接comTableRowOne.getCell(0).setText("序号"); 赋值的。
            // 第一行的其他列需要创建后才能赋值 comTableRowOne.addNewTableCell().setText("作品类型");
            for(int i = 0; i < strs.length; i++){
                if (i == 0){
                    comTableRowOne.getCell(0).setText(strs[i]);
                }else {
                    comTableRowOne.addNewTableCell().setText(strs[i]);
                }
            }


//            comTableRowOne.getCell(0).setText("序号");
//            comTableRowOne.addNewTableCell().setText("名称");
//            comTableRowOne.addNewTableCell().setText("审批人");
//            comTableRowOne.addNewTableCell().setText("审批时间");
//            comTableRowOne.addNewTableCell().setText("审批意见");

            int wid = 8500/strs.length;
            for(int i = 0; i < strs.length; i++) {
                setCellWitchAndAlign(comTableRowOne.getCell(i),Integer.toString(wid), STVerticalJc.CENTER, STJc.CENTER);
            }
                // 表格标题剧中+单元格大小设置
//            setCellWitchAndAlign(comTableRowOne.getCell(0),"700", STVerticalJc.CENTER, STJc.CENTER);
//            setCellWitchAndAlign(comTableRowOne.getCell(1),"1500",STVerticalJc.CENTER,STJc.CENTER);
//            setCellWitchAndAlign(comTableRowOne.getCell(2),"1500",STVerticalJc.CENTER,STJc.CENTER);
//            setCellWitchAndAlign(comTableRowOne.getCell(3),"1500",STVerticalJc.CENTER,STJc.CENTER);
//            setCellWitchAndAlign(comTableRowOne.getCell(4),"3400",STVerticalJc.CENTER,STJc.CENTER);
            XWPFTableRow comTableRow = null;
            // 生成表格内容
            // 根据上面的表格标题 确定列数，所以下面创建的是行数。
            // comTableRow.getCell(1).setText(user.getName()); 确定第几列 然后创建赋值
            // 注意：我这边是列数较少固定的，如果列数不固定可循环创建上面的列数
            for (int i=0;i < list.size();i++) {
                comTableRow = ComTable.createRow();

                // 表格内容的填充
                TableEntity tab = list.get(i);

                /*-------------------变量替换（get）------------------------*/
//                comTableRow.getCell(0).setText(((Integer)(i+1)).toString());
//                comTableRow.getCell(1).setText(tab.getQuery01());
//                comTableRow.getCell(2).setText(tab.getQuery02());
//                comTableRow.getCell(3).setText(tab.getQuery03());
//                comTableRow.getCell(4).setText(tab.getQuery04());
                /*-------------------变量替换（get）------------------------*/


                for(int j = 0; j < strs.length; j++) {
                    // 表格内容的填充
                    if(j == 0)
                        comTableRow.getCell(0).setText(((Integer)(i+1)).toString());
                    else
                        comTableRow.getCell(j).setText(getBean(tab,Integer.toString(j+1)));
                }
                for(int s = 0; s < strs.length; s++) {
                    // 表格内容剧中+单元格大小设置
                    setCellWitchAndAlign(comTableRow.getCell(s),Integer.toString(wid),STVerticalJc.CENTER,STJc.CENTER);
                }
                // 表格内容剧中+单元格大小设置
//                setCellWitchAndAlign(comTableRow.getCell(0),"700",STVerticalJc.CENTER,STJc.CENTER);
//                setCellWitchAndAlign(comTableRow.getCell(1),"1500",STVerticalJc.CENTER,STJc.CENTER);
//                setCellWitchAndAlign(comTableRow.getCell(2),"1500",STVerticalJc.CENTER,STJc.CENTER);
//                setCellWitchAndAlign(comTableRow.getCell(3),"1500",STVerticalJc.CENTER,STJc.CENTER);
//                setCellWitchAndAlign(comTableRow.getCell(4),"3400",STVerticalJc.CENTER,STJc.CENTER);
            }


            //输出word内容文件流，文件形式
            FileOutputStream fos = new FileOutputStream(outFilePath);
            document.write(fos);
            fos.flush();
            fos.close();

        } catch (Exception e1) {
            e1.printStackTrace();
        }finally{

        }
    }


    // 给生成的表格设置样式
    private static void setCellWitchAndAlign(XWPFTableCell cell, String width, STVerticalJc.Enum typeEnum, STJc.Enum align){
        CTTc cttc = cell.getCTTc();
        CTTcPr ctPr = cttc.addNewTcPr();
        ctPr.addNewVAlign().setVal(typeEnum);
        cttc.getPList().get(0).addNewPPr().addNewJc().setVal(align);
        CTTblWidth ctTblWidth = (ctPr != null && ctPr.isSetTcW() && ctPr.getTcW()!=null &&ctPr.getTcW().getW()!=null) ? ctPr.getTcW(): ctPr.addNewTcW();
        if(StringUtils.isNotBlank(width)){
            ctTblWidth.setW(new BigInteger(width));
            ctTblWidth.setType(STTblWidth.DXA);

        }
    }


    private static String getBean(Object object, String methond) {
        JexlEngine jexl = new JexlBuilder().create();
        JexlContext jc = new MapContext();
        jc.set("tab",object);
        String allM;
        allM = "tab.getQuery0" + methond + "()";
        JexlExpression e = jexl.createExpression(allM);
        Object o = e.evaluate(jc);
        System.out.println(" >>>> 执行方法====="+allM);
        return o.toString();
    }

}
